package com.ssmTest.controller;


import com.ssmTest.domian.Log;
import com.ssmTest.domian.User;
import com.ssmTest.service.LogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
@Aspect
public class LogAspect {

    @Autowired
    private LogService logService;

    @Autowired
    private HttpServletRequest request;

    /*
    环绕通知
     */
    @Around("execution(* com.ssmTest.controller.*.*(..))")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        //创建起始时间
        Date start = new Date();
        //执行目标方法
        Object proceed = pjp.proceed();
        long cost = new Date().getTime()-start.getTime();

        //获取目标方法类名,方法名
        String className = pjp.getTarget().getClass().getName();
        String methodName = pjp.getSignature().getName();

        User user = (User)request.getSession().getAttribute("loginUser");
        String username="";
        if (user!=null){
            username=user.getName();
        }else {
            username=request.getParameter("name");
        }

        Log log =new Log();
        log.setName(username);
        log.setUrl("/"+className+"/"+methodName);
        log.setTime(new Date());
        log.setCost(cost);

        System.out.println("Log已记录"+log);
        logService.addLogs(log);

        return proceed;
    }

}
